﻿Imports Aspose.Words
Imports System.Net
Imports System.IO
Imports System.IO.Path
Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class Control_QuanLyHoSoThongBaoThuHoi_QuyetDinh
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
    Dim itm As New ListItem("--- Chọn ---", "  ")
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            If Not Request("Certifiedid") Is Nothing AndAlso Request("Certifiedid") <> 0 Then
                hidID.Value = Request("Certifiedid")
                Load2Grid()
            End If
        End If
    End Sub
    Protected Sub Load2Grid()
        Using _data As New VSEntities

            Dim _curHuyenId As Integer = Session("HuyenId")
            'load List PrositionDict
            Dim _j = (From q In _data.PositionDicts Order By q.Sort Select q).ToList
            With ddlCertifiedSignerPosition
                .DataSource = _j
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With
            With ddlCertifiedSignFor
                .DataSource = _j
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With
            'load list StaffDict
            Dim _SN = (From q In _data.StaffDicts Where q.ProvinceId = _curHuyenId Order By q.Sort Select q).ToList
            With ddlCertifiedSignerName
                .DataSource = _SN
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With
            Dim _BH = (From q In _data.StaffDicts Where q.ProvinceId = _curHuyenId Order By q.Sort Select q).ToList
            With ddlCertifiedBeHaft
                .DataSource = _BH
                .DataValueField = "Name"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", " "))
            End With


            'load giấy đề nghị nếu có rồi
            'Dim intUserId As Integer = IIf(IsNothing(Session("UserID")), 0, Session("UserID"))
            'Dim use = (From q In _data.Users Where q.UserId = intUserId Select q.UserName).FirstOrDefault

            Dim p = (From q In _data.CertifiedHouseholds Where q.CertifiedID = hidID.Value Select q).FirstOrDefault

            CapNhatMCC.Visible = False
            If Not p Is Nothing Then
                'show link Update MCC
                If Not p.SoBienNhan Is Nothing Then
                    Using abc As New AutoDevModel.AutoDevEntities
                        Dim kkkk = (From q In abc.HoSoes Where q.SoBienNhan = p.SoBienNhan And q.HuyenId = _curHuyenId Select q).FirstOrDefault
                        If Not kkkk Is Nothing Then
                            CapNhatMCC.Visible = True
                            hplLinkMcc.NavigateUrl = "../../Page/TiepNhan/UpdateMcc.aspx?s=" & kkkk.SoBienNhan.ToString
                            hplLinkMcc.Text = "đây"
                        End If
                    End Using
                End If

                If Not p.CertifiedCode Is Nothing AndAlso p.CertifiedCode <> "" Then
                    txtCertifiedCode.Text = p.CertifiedCode
                    If Not p.CertifiedDate Is Nothing Then
                        txtCertifiedDate.Text = CType(p.CertifiedDate, Date).ToString("dd/MM/yyyy")
                    Else

                        txtCertifiedDate.Text = Now.Date.ToString("dd/MM/yyyy")
                    End If
                Else
                End If
                'thong tin ca nhan


                'load CertifiedProvinderOrg by DeptCertifieds
                Dim _l = (From q In _data.DeptCertifieds Where q.ProvinceId = _curHuyenId Order By q.Sort Select q).ToList

                With ddlCertifiedProviderOrg
                    .DataSource = _l
                    .DataValueField = "Name"
                    .DataTextField = "Name"
                    .DataBind()
                    .Items.Insert(0, itm)
                End With
                'load CertifiedDeptName by DeptCertifieds
                With ddlCertifiedDeptName
                    .DataSource = _l
                    .DataValueField = "Name"
                    .DataTextField = "Name"
                    .DataBind()
                    .Items.Insert(0, itm)
                End With
                Dim _DoViCap = (From q In _data.DeptCertifieds Where q.ProvinceId = _curHuyenId And q.Code = "001" Order By q.Sort Select q.Name).FirstOrDefault
                Dim _PhongBanCap = (From q In _data.DeptCertifieds Where q.ProvinceId = _curHuyenId And q.Code = "002" Order By q.Sort Select q.Name).FirstOrDefault

                'thông tin hộ
                txtBiz_VietNam.Text = IIf(IsNothing(p.Biz_VietName) = True, "", p.Biz_VietName) 'tên hộ kinh doanh
                txtOw_Name.Text = IIf(IsNothing(p.Ow_Name) = True, "", p.Ow_Name) 'tên hộ đại diện hộ
                txtBiz_HeadOffice.Text = IIf(IsNothing(p.Biz_HeadOffice) = True, "", p.Biz_HeadOffice) 'địa chỉ kinh doanh
                txtOw_Resident.Text = IIf(IsNothing(p.Ow_Resident) = True, "", p.Ow_Resident) 'địa chỉ kinh doanh
                'lấy thông tin Quyết định
                Dim _qd = (From q In _data.CertifiedHouseQuyetDinhs Where q.CertifiedID = hidID.Value And q.HuyenId = _curHuyenId Select q).FirstOrDefault
                If Not _qd Is Nothing Then
                    If Not _qd.SoQuyetDinh Is Nothing AndAlso _qd.SoQuyetDinh <> "" Then
                        txtSoQuyetDinh.Text = _qd.SoQuyetDinh
                        If Not _qd.NgayQuyetDinh Is Nothing Then
                            txtNgayQuyetDinh.Text = CType(_qd.NgayQuyetDinh, Date).ToString("dd/MM/yyyy")
                        Else

                            txtNgayQuyetDinh.Text = Now.Date.ToString("dd/MM/yyyy")
                        End If
                    Else
                        txtSoQuyetDinh.Text = btnSoQuyetDinh()
                    End If
                    'txtSoBienBan.Text = IIf(IsNothing(_qd.SoBienBan) = True, "", _qd.SoBienBan) 'số biên bản
                    'If Not _qd.NgayLapBienBan Is Nothing Then
                    'txtNgayLapBienBan.Text = CType(_qd.NgayLapBienBan, Date).ToString("dd/MM/yyyy")
                    'End If
                    txtCanCuThongBao.Text = IIf(IsNothing(_qd.CanCuThongBao) = True, "", _qd.CanCuThongBao) ' căn cứ thông báo
                    'ngày hiệu lực quyết định
                    If Not _qd.NgayHieuLuc Is Nothing Then
                        txtNgayHieuLuc.Text = CType(_qd.NgayHieuLuc, Date).ToString("dd/MM/yyyy")
                    Else

                        txtNgayHieuLuc.Text = Now.Date.ToString("dd/MM/yyyy")
                    End If
                    'Đơn vị cấp
                    If Not _qd.TenCoQuan Is Nothing And _qd.TenCoQuan <> "" Then
                        ddlCertifiedProviderOrg.SelectedValue = _qd.TenCoQuan
                    Else
                        ddlCertifiedProviderOrg.SelectedValue = _DoViCap
                    End If
                    'Phòng ban cấp
                    If Not _qd.TenPhongBan Is Nothing And _qd.TenPhongBan <> "" Then
                        ddlCertifiedDeptName.SelectedValue = _qd.TenPhongBan
                    Else
                        ddlCertifiedDeptName.SelectedValue = _PhongBanCap
                    End If
                    'Người ký
                    If Not _qd.TenNguoiKy Is Nothing Then
                        ddlCertifiedSignerName.SelectedValue = _qd.TenNguoiKy
                    Else
                        ddlCertifiedSignerName.SelectedValue = ""
                    End If
                    'Chức vụ người ký
                    If Not _qd.ChucVuNguoiKy Is Nothing Then
                        ddlCertifiedSignerPosition.SelectedValue = _qd.ChucVuNguoiKy
                    Else
                        ddlCertifiedSignerPosition.SelectedValue = ""
                    End If
                Else
                    txtSoQuyetDinh.Text = btnSoQuyetDinh()
                    ddlCertifiedProviderOrg.SelectedValue = _DoViCap
                    ddlCertifiedDeptName.SelectedValue = _PhongBanCap
                    ddlCertifiedSignerName.SelectedValue = ""
                    ddlCertifiedSignerPosition.SelectedValue = ""
                End If

            End If

        End Using
    End Sub
    Protected Function btnSoQuyetDinh() As String
        Dim strCode As String = ""
        Dim _curHuyenId As Integer = Session("HuyenId")
        Using _data As New VSEntities
            Dim curCode As String = (From q In _data.Provinces Where q.Id = _curHuyenId Select q.Code).FirstOrDefault
            Dim max As String = (From q In _data.CertifiedHouseQuyetDinhs Where q.HuyenId = _curHuyenId And q.SoQuyetDinh.Contains(curCode) And q.NgayQuyetDinh > "2014/01/01" Order By q.SoQuyetDinh Descending Select q.SoQuyetDinh).FirstOrDefault
            '52I2416
            Dim HuyenCode = (From q In _data.Provinces Where q.Id = _curHuyenId Select q.Code).FirstOrDefault & "QD"
            Try
                Dim _new As Integer = CType(max.Replace(HuyenCode, ""), Integer) + 1
                If _new > 0 Then
                    strCode = HuyenCode & _new.ToString.PadLeft(5)
                Else
                    strCode = HuyenCode & "8000" & _new.ToString.PadLeft(5)
                End If
            Catch ex As Exception
                strCode = HuyenCode & "8000" & "1"
            End Try
            hidSoQuyetDinh.Value = strCode ' lưu vao hidden field để lưu
            txtNgayQuyetDinh.Text = Now.Date.ToString("dd/MM/yyyy")
            Return strCode

        End Using
    End Function
    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx")
    End Sub

    Protected Sub btnExportWord_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportWord.Click
        UpdateThongtin()
        Dim strDocFile = getDocFile()
        Dim strFileName As String = strDocFile.Split("\")(strDocFile.Split("\").Length - 1)
        Excute_Javascript("SetDownFile('" & MainDomain & "QDGCN/" & strFileName & "');", Me.Page)
    End Sub
    Protected Sub btnExportPdf_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportPdf.Click
        UpdateThongtin()
        Dim strDocFile = getDocFile()
        'save PDF
        Dim strPdfFile As String = strDocFile.Replace(".doc", ".pdf")
        If Not File.Exists(strPdfFile) Then
            Dim licenseFile As String = Server.MapPath("~") & "\bin\Aspose.Words.lic"
            If (File.Exists(licenseFile)) Then
                Dim license As Aspose.Words.License = New Aspose.Words.License()
                license.SetLicense(licenseFile)
                Dim doc As Aspose.Words.Document = New Aspose.Words.Document(strDocFile)
                doc.Save(strPdfFile, SaveFormat.Pdf)
                If Not IsNothing(doc) Then
                    doc = Nothing
                End If
            End If
            Dim applicationPath As String = Server.MapPath(Request.ApplicationPath)
            Dim strFileName As String = strPdfFile.Split("\")(strPdfFile.Split("\").Length - 1)

            Response.Redirect(MainDomain & "QDGCN/" & strFileName)
        End If



    End Sub

    Function getDocFile() As String
        Dim curHuyenId As Integer = Session("HuyenId")
        Dim strResult As String = ""
        Try
            Dim applicationPath As String = Server.MapPath(Request.ApplicationPath)
            If Not applicationPath.EndsWith("\") Then
                applicationPath = applicationPath + "\"
            End If
            Dim licenseFile As String = Path.Combine(applicationPath, "bin\Aspose.Words.lic")
            If (File.Exists(licenseFile)) Then
                Dim license As Aspose.Words.License = New Aspose.Words.License()
                license.SetLicense(licenseFile)

                Dim strDocFile As String = applicationPath & "Template\QuyetDinhThuHoi.doc"
                Dim doc As Aspose.Words.Document = New Aspose.Words.Document(strDocFile)

                Dim cls As New clsDAPrint
                Dim dt As DataTable = cls.CertifiedHouseholdQuyetDinhSelectById(hidID.Value, curHuyenId)
                cls.Destructor()
                cls = Nothing
                If dt.Rows.Count > 0 Then
                    doc.MailMerge.Execute(dt)
                    Dim builder As DocumentBuilder = New DocumentBuilder(doc)
                    Using _data As New VSEntities
                        Dim _qd = (From q In _data.CertifiedHouseQuyetDinhs Where q.CertifiedID = hidID.Value And q.HuyenId = curHuyenId Select q).FirstOrDefault
                        If Not _qd Is Nothing Then
                            'ngày ra Quyết định
                            Dim _date As Date = CType(_qd.NgayQuyetDinh, Date)
                            Dim _H = (From j In _data.Provinces Where j.Id = curHuyenId Select j).FirstOrDefault
                            builder.MoveToMergeField("Ngayraquyetdinh")
                            If Not _qd.NgayQuyetDinh Is Nothing Then
                                builder.Write(_H.Title & ",ngày " & _date.Day & " tháng " & _date.Month & " năm " & _date.Year)
                            Else
                                builder.Write("")
                            End If
                            builder.MoveToMergeField("DOVIQUANLY")
                            If Not _qd.TenPhongBan Is Nothing And _qd.TenPhongBan <> "" Then
                                builder.Write(_qd.TenPhongBan) 'tên phong ban
                            Else
                                builder.Write("")
                            End If
                            'lấy tên hộ kinh doanh
                            Dim _Biz = (From h In _data.CertifiedHouseholds Where h.CertifiedID = _qd.CertifiedID Select h).FirstOrDefault

                            If Not _Biz Is Nothing Then
                                builder.MoveToMergeField("DAIDIENHOKINHDOANH")
                                Dim _strBiz_VietName As String = IIf(IsNothing(_Biz.Biz_VietName) = True, "", _Biz.Biz_VietName)
                                If Not _strBiz_VietName Is Nothing And _strBiz_VietName <> "" Then
                                    builder.Write(_strBiz_VietName) 'tên hộ kinh doanh
                                Else
                                    builder.Write("")
                                End If


                                'ngay sinh
                                Dim _Ow_BirthDate_Name As String = ""
                                Dim _ngaysinh = Len(_Biz.Ow_BirthDate)
                                Dim _strNgaySinh As String = Replace(_Biz.Ow_BirthDate, "/", "")
                                If Not _Biz.Ow_BirthDate Is Nothing AndAlso _Biz.Ow_BirthDate <> "01/01/1900" Then
                                    If IsDate(_Biz.Ow_BirthDate) Then
                                        _Ow_BirthDate_Name = CType(_Biz.Ow_BirthDate, Date).ToString("dd/MM/yyyy") 'ngày tháng năm sinh
                                    Else
                                        If _ngaysinh >= 8 Then
                                            Dim _nam As String = Mid(_strNgaySinh, 5, 8)
                                            Dim _thang As String = Mid(_strNgaySinh, 3, 2)
                                            Dim _ngay As String = Mid(_strNgaySinh, 1, 2)
                                            If (Int32.Parse(_thang) = 0) And (Int32.Parse(_ngay) = 0) Then
                                                _Ow_BirthDate_Name = _nam 'ngày tháng năm sinh
                                            Else
                                                _Ow_BirthDate_Name = _ngay & "/" & _thang & "/" & _nam 'ngày tháng năm sinh
                                            End If
                                        ElseIf _ngaysinh = 4 Then
                                            _Ow_BirthDate_Name = _strNgaySinh 'ngày tháng năm sinh
                                        End If
                                    End If

                                    builder.MoveToMergeField("Ow_BirthDate_Name")
                                    If Not _Ow_BirthDate_Name Is Nothing Then
                                        builder.Write(_Ow_BirthDate_Name)
                                    Else
                                        builder.Write(_Biz.Ow_BirthDate)
                                    End If
                                End If
                            End If

                            ' loại giấy tờ
                            If _Biz.Ow_Doc_ID = "" Or _Biz.Ow_Doc_ID = "0" Then
                                builder.MoveToMergeField("Ow_Doc_ID_Name")
                                builder.Write("Giấy chứng minh nhân dân")
                            Else
                                Dim strLoaiGiay = (From q In _data.CertifiedPaperDicts Where q.Id = _Biz.Ow_Doc_ID Select q).FirstOrDefault
                                If Not strLoaiGiay Is Nothing Then
                                    builder.MoveToMergeField("Ow_Doc_ID_Name")
                                    builder.Write(strLoaiGiay.Name)
                                End If
                            End If
                        End If
                    End Using
                    strResult = applicationPath & "QDGCN"
                    If Not Directory.Exists(strResult) Then
                        Directory.CreateDirectory(strResult)
                    End If
                    If Not strResult.EndsWith("\") Then
                        strResult = strResult + "\"
                    End If
                    'set filename = soCN

                    strResult &= txtSoQuyetDinh.Text & "-" & Format(Now, "yyyyMMddfff") & ".doc"
                    doc.Save(strResult, Aspose.Words.SaveFormat.Doc)
                    If Not IsNothing(doc) Then
                        doc = Nothing
                    End If

                End If
            End If
        Catch ex As Exception
            log4net.Config.XmlConfigurator.Configure()
            log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
            Excute_Javascript("Alertbox('Cập nhật thất bại.');window.location ='../../Page/QuanLyHoSoThongBaoThuHoi/List.aspx';", Me.Page, True)
        End Try

        Return strResult
    End Function

    Protected Sub UpdateThongtin()
        Using _data As New VSEntities
            Dim _curHuyenId As Integer = Session("HuyenId")
            Dim p = (From k In _data.CertifiedHouseholds Where k.CertifiedID = hidID.Value And k.ProvinceId = _curHuyenId Select k).FirstOrDefault
            If Not p Is Nothing Then
                Dim _Checktb = (From q In _data.CertifiedHouseQuyetDinhs Where q.CertifiedID = hidID.Value And q.HuyenId = _curHuyenId Select q).FirstOrDefault
                If _Checktb Is Nothing Then
                    Dim _qd As New VSModel.CertifiedHouseQuyetDinh
                    Try
                        _qd.SoQuyetDinh = txtSoQuyetDinh.Text.Trim()
                        _qd.NgayQuyetDinh = StringToDate(txtNgayQuyetDinh.Text.Trim())
                        _qd.CanCuThongBao = txtCanCuThongBao.Text.Trim()
                        _qd.NgayHieuLuc = StringToDate(txtNgayHieuLuc.Text.Trim())
                        _qd.TenCoQuan = ddlCertifiedProviderOrg.SelectedValue 'đơn vị cấp
                        _qd.TenPhongBan = ddlCertifiedDeptName.SelectedValue ' phòng ban cấp
                        _qd.ChucVuNguoiKy = ddlCertifiedSignerPosition.SelectedValue 'chức vụ người ký
                        _qd.TenNguoiKy = ddlCertifiedSignerName.SelectedValue ' tên người ký
                        _qd.NgayTao = Now
                        _qd.NguoiTao = Session("UserName")
                        _qd.HuyenId = Session("HuyenId")
                        _qd.StatusId = TinhTrangHoSo.Daduyet
                        _qd.CertifiedID = hidID.Value
                        _data.CertifiedHouseQuyetDinhs.AddObject(_qd)
                        Dim strLog As String = "Quyết định:" & txtCertifiedCode.Text.Trim() & ", tên hộ: " & txtBiz_VietNam.Text.Trim()
                        Insert_App_Log("Insert  Quyết định:" & strLog & "", Function_Name.CertifiedChamDut, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                    Catch ex As Exception
                        log4net.Config.XmlConfigurator.Configure()
                        log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                    End Try
                Else
                    Try
                        _Checktb.SoQuyetDinh = txtSoQuyetDinh.Text.Trim()
                        _Checktb.NgayQuyetDinh = StringToDate(txtNgayQuyetDinh.Text.Trim())
                        _Checktb.CanCuThongBao = txtCanCuThongBao.Text.Trim()
                        _Checktb.NgayHieuLuc = StringToDate(txtNgayHieuLuc.Text.Trim())
                        _Checktb.TenCoQuan = ddlCertifiedProviderOrg.SelectedValue 'đơn vị cấp
                        _Checktb.TenPhongBan = ddlCertifiedDeptName.SelectedValue ' phòng ban cấp
                        _Checktb.ChucVuNguoiKy = ddlCertifiedSignerPosition.SelectedValue 'chức vụ người ký
                        _Checktb.TenNguoiKy = ddlCertifiedSignerName.SelectedValue ' tên người ký
                        _Checktb.NgaySua = Now
                        _Checktb.NguoiSua = Session("UserName")
                        _Checktb.HuyenId = Session("HuyenId")
                        Dim strLog As String = "Quyết định:" & txtCertifiedCode.Text.Trim() & ", tên hộ: " & txtBiz_VietNam.Text.Trim()
                        Insert_App_Log("Edit  Quyết định:" & strLog & "", Function_Name.CertifiedChamDut, Audit_Type.Edit, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                    Catch ex As Exception
                        log4net.Config.XmlConfigurator.Configure()
                        log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                    End Try
                End If
                _data.SaveChanges()
            End If
        End Using
    End Sub
End Class

